#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
/* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建套接字
	if (-1 == sockfd)
	{
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6666);
	addr.sin_addr.s_addr = inet_addr("192.168.1.121");

	if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))) // 绑定
	{
		perror("bind");
		return -1;
	}

	if (-1 == listen(sockfd, 3)) // 监听
	{
		perror("listen");
		return -1;
	}
F:
	printf("等待客户端连接\n");

	struct sockaddr_in client_addr;
	socklen_t client_addrlen = sizeof(client_addr);
	int connfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addrlen); // 等待连接
	if (connfd == -1)
	{
		perror("accept");
		return -1;
	}
	printf("连接成功\n");
	char name[100] = "xiaoming";
	char pwd[100] = "123456";
	while (1)
	{
		char rev_name[100];
		char rev_pwd[100];
		read(connfd, rev_name, sizeof(rev_name));
		read(connfd, rev_pwd, sizeof(rev_pwd));
		if ((strcmp(name, rev_name) == 0) && (strcmp(pwd, rev_pwd) == 0))
		{
			// 登录成功
			write(connfd, "login is ok", sizeof("login is ok")); // 发送登录成功指令
			printf("用户：%s登录成功",rev_name);
		}
		else
		{
			printf("用户：%s登录失败",rev_name);
			write(connfd, "login fail!", sizeof("login fail!")); // 发送登录失败指令 
			goto F;
		}
	}
	close(connfd);
	close(sockfd);
	return 0;
}